package com.kuai.todo1.controller;

import com.kuai.todo1.model.User;
import com.kuai.todo1.service.UserService;
import com.kuai.todo1.utils.JwtUtil;

import lombok.extern.slf4j.Slf4j;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/api/users")
@Slf4j
public class UserController {

    @Autowired
    private UserService userService;

    @Autowired
    private JwtUtil jwtUtil;

    @PostMapping("/register")
    public ResponseEntity<String> register(@RequestBody User user) {

        Boolean bo = userService.registerUser(user);

        if (bo) {
            log.info("User registered successfully!");
            return ResponseEntity.ok("用户注册成功！");
        } else {
            // "用户名已被注册，请选择其他用户名。"
            System.out.println("用户名已被注册，请选择其他用户名。");
            log.warn("用户名已被注册，请选择其他用户名!");
            return ResponseEntity
                    .status(HttpStatus.UNAUTHORIZED)
                    .body("用户名已被注册，请选择其他用户名!");
            // .body("Invalid username or password!");
        }
    }

    @PostMapping("/login")
    public ResponseEntity<String> login(@RequestParam String username, @RequestParam String password) {
        if (userService.loginUser(username, password)) {

            String token = jwtUtil.generateToken(username);
            log.info("login successfully!");
            return ResponseEntity.ok(token);

            // return ResponseEntity.ok("Login successful!");
        } else {
            log.info("登录鉴权失败!");
            return ResponseEntity
                    .status(HttpStatus.UNAUTHORIZED)
                    .body("Invalid username or password!");
        }
    }

    @GetMapping("/validate")
    public ResponseEntity<String> validateToken(@RequestHeader("Authorization") String authorizationHeader) {

        String token = authorizationHeader;
        // System.out.println("62 Authorization Header -> " + token);

        log.info("62 Authorization Header -> " + token);

        String username = jwtUtil.extractedUsername(token);
        // System.out.println("63 username -> " + username);

        if (username == null || !jwtUtil.validateToken(token, username)) {
        log.warn("63 error username -> " + username);
            return ResponseEntity
                    .status(HttpStatus.UNAUTHORIZED)
                    .body("Invalid token");
        }

        return ResponseEntity.ok("Token is valid");
    }

}
